package com.calabar.flume.tcp.server;

import io.netty.channel.ChannelHandlerAdapter;
import io.netty.channel.ChannelHandlerContext;

import java.nio.ByteBuffer;
import java.util.ArrayList;
import java.util.List;

/**
 * @author hdfs
 */
public class MyServerHandler extends ChannelHandlerAdapter {
    private static int j = 0;

    @Override
    public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
        long start = System.currentTimeMillis();
        System.out.println("解析开始时间："+start);
        List<Float> data = new ArrayList<Float>();
        byte[] bytes = (byte[]) msg;
        ByteBuffer bb = ByteBuffer.wrap(bytes);
        for (int i = 0; i < bytes.length / 4; i++) {
            byte[] elm = new byte[4];
            bb.get(elm, 0, 4);
            data.add(getFloat(elm)*123/4*2-5);
        }
        MyTCPSocketServer.queue.offer(data);
        long end = System.currentTimeMillis();
        System.out.println("解析结束时间："+end);
        System.out.println("第" + (j++) + "条,数据解析耗时：" + (end - start));
    }

    public static int getInt(byte[] bytes) {
        return (0xff & bytes[0]) | (0xff00 & (bytes[1] << 8)) | (0xff0000 & (bytes[2] << 16)) | (0xff000000 & (bytes[3] << 24));
    }

    public static float getFloat(byte[] bytes) {
        return Float.intBitsToFloat(getInt(bytes));
    }
}